package com.net.library.nettoken;

import android.content.Context;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import com.net.library.bean.IRequstCode;
import com.net.library.interfaces.RequestListener;
import com.net.library.util.HttpsUtil;
import okhttp3.OkHttpClient;
import retrofit2.Call;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

import java.util.concurrent.TimeUnit;

/**
 * Created by 吴昶 on 2018/8/15.
 */
public class RetrofitTokenServer {

    private static RetrofitTokenServer retrofitTokenServer;
    private Retrofit retrofitToken;
    private Retrofit retrofit;
    private Context context;
    private String url;

    /**
     * 单例 再 MyApplication 中初始化调用
     * 防止重复多次 新建对象
     * @return
     */
    public static RetrofitTokenServer getInstance(){
        if(retrofitTokenServer ==null){
            retrofitTokenServer =new RetrofitTokenServer();
        }
        return retrofitTokenServer;
    }

    /**
     * 初始化 Retrofit
     * @param context
     * @param url
     */
    public void init(Context context, String url){
        this.context=context;
        this.url=url;
        OkHttpClient httpClient = new OkHttpClient().newBuilder()
                .addInterceptor(new MyHttpLoggingInterceptor())
                .retryOnConnectionFailure(true)
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(30,TimeUnit.SECONDS)
                .sslSocketFactory(HttpsUtil.getSslSocketFactory())
                .hostnameVerifier(HttpsUtil.getHostnameVerifier())
                .build();

        Gson gson=new GsonBuilder().setLenient().create();

        retrofit=new Retrofit.Builder()
                .baseUrl(url)
                .client(httpClient)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
    }

    public void initToken(){
        Gson gson=new GsonBuilder().setLenient().create();

        retrofitToken=new Retrofit.Builder()
                .baseUrl(url)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .build();
    }


    /**
     * 获取接口对象  本例中主要是 BlogServer
     * @param clazz
     * @param <T>
     * @return
     */
    public <T> T createCall(Class<T> clazz){
        return retrofit.create(clazz);
    }

    public <T> T createCallToken(Class<T> clazz){
        return retrofitToken.create(clazz);
    }

    /**
     * 设置通用的数据请求方法
     * @param requestCall  call
     * @param requestCode  反馈码，自填，可不要
     * @param requestListener  数据获取的回调监听
     * @param <T>
     */
    public <T extends IRequstCode> void enqueue(Call<T> requestCall, final int requestCode, final RequestListener<T> requestListener){
        RetrofitConnection.getInstance().enqueue(context,requestCall,requestCode,requestListener);
    }


}
